package com.example.framework.security.config;

import com.example.framework.security.core.context.TransmittableThreadLocalSecurityContextHolderStrategy;
import com.example.framework.security.core.decoder.FeignTokenDecoder;
import com.example.framework.security.core.filter.TokenAuthenticationFilter;
import com.example.framework.security.core.handler.AccessDeniedHandlerImpl;
import com.example.framework.security.core.handler.AuthenticationEntryPointImpl;
import com.example.framework.security.core.handler.LogoutHandlerImpl;
import com.example.framework.security.core.handler.LogoutSuccessHandlerImpl;
import com.example.framework.security.core.interceptor.FeignInterceptor;
import com.example.framework.security.core.resolver.LoginUserHandlerMethodArgument;
import com.example.framework.security.core.util.JwtTokenUtils;
import com.example.framework.web.core.handler.GlobalExceptionHandler;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@RequiredArgsConstructor
@AutoConfiguration // 非启动模块的配置类注解
@EnableConfigurationProperties(SecurityProperties.class)
public class SecurityAutoConfiguration implements WebMvcConfigurer {

    private final SecurityProperties securityProperties;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public JwtTokenUtils jwtTokenUtil() {
        return new JwtTokenUtils(securityProperties);
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new LoginUserHandlerMethodArgument(jwtTokenUtil()));
    }

    /**
     * 认证失败处理类 Bean
     */
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return new AuthenticationEntryPointImpl();
    }

    /**
     * 权限不够处理器 Bean
     */
    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return new AccessDeniedHandlerImpl();
    }

    @Bean
    public LogoutHandler logoutHandler(GlobalExceptionHandler globalExceptionHandler) {
        return new LogoutHandlerImpl(securityProperties, jwtTokenUtil(), globalExceptionHandler);
    }

    /**
     * 退出处理类 Bean
     */
    @Bean
    public LogoutSuccessHandler logoutSuccessHandler() {
        return new LogoutSuccessHandlerImpl();
    }

    @Bean
    public AuthorizeRequestsCustomizer authorizeRequestsCustomizer() {
        return new AuthorizeRequestsCustomizer();
    }

    /**
     * Token 认证过滤器 Bean
     */
    @Bean
    public TokenAuthenticationFilter authenticationTokenFilter(SecurityProperties securityProperties, GlobalExceptionHandler globalExceptionHandler,
                                                               JwtTokenUtils jwtTokenUtils) {
        return new TokenAuthenticationFilter(securityProperties, globalExceptionHandler, jwtTokenUtils);
    }

    @Bean
    public RequestInterceptor feignInterceptor() {
        return new FeignInterceptor(securityProperties);
    }

    @Bean
    public Decoder feignDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        return new FeignTokenDecoder(messageConverters, securityProperties);
    }

    /**
     * 声明调用 {@link SecurityContextHolder#setStrategyName(String)} 方法，
     * 设置使用 {@link TransmittableThreadLocalSecurityContextHolderStrategy} 作为 Security 的上下文策略
     */
    @Bean
    public MethodInvokingFactoryBean securityContextHolderMethodInvokingFactoryBean() {
        MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
        methodInvokingFactoryBean.setTargetClass(SecurityContextHolder.class);
        methodInvokingFactoryBean.setTargetMethod("setStrategyName");
        methodInvokingFactoryBean.setArguments(TransmittableThreadLocalSecurityContextHolderStrategy.class.getName());
        return methodInvokingFactoryBean;
    }
}
